package ptumall.config;

import jdk.nashorn.internal.ir.RuntimeNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

@Configuration
@EnableOpenApi
public class SwaggerConfig {
    @Value("${swagger.enable}")
    Boolean swaggerEnabled;

    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                //是否开启swagger
                .enable(swaggerEnabled)
                .select()
                .apis(RequestHandlerSelectors.basePackage("ptumall.controller"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(Collections.singletonList(securityScheme()))
                .securityContexts(Arrays.asList(tokenContext()));
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("ptu","http://ptu.com","123@qq.com");
        return new ApiInfo(
                "ptu mall",
                "ptu mall 测试接口文档",
                "v1.0",
                "http://ptu.com",
                contact,
                "Apache 2.0",
                "http://apache.org/licenses/LICENSE-2.0",
                new ArrayList()){
        };
    }
    @Bean
    SecurityScheme securityScheme() {
        return new ApiKey("token", "token", "header");
    }
   private SecurityContext tokenContext(){
        return SecurityContext.builder()
                .securityReferences(Arrays.asList(SecurityReference.builder().scopes(new AuthorizationScope[0]).reference("token").build()))
                .operationSelector(o->o.requestMappingPattern().matches("/.*")).build();
   }

   //127.0.0.1:8088/swagger-ui/index.html,在实体类上人性化修改，在Controller上加上api注解
 }
